# -*- coding: utf-8 -*-
from django.http import Http404
from django.db import models
from django.shortcuts import get_object_or_404, get_list_or_404
from Resource import resource_registry


def get_list_or_create(request, key, app, model):
    Class = models.get_model(app, model)
    if Class is None:
        raise Http404("can not find model: %s/%s" % (app, model))
    try:
        resource = resource_registry[Class][key]
    except KeyError:
        raise Http404("the model does not support rest views")
    if request.method == "GET":
        # 获取列表
        return resource.get_list(request, Class)
    elif request.method == "POST":
        # 创建一条记录
        return resource.create(request, Class)


def rud(request, key, app, model, pk):
    # read, update, delete 操作
    Class = models.get_model(app, model)
    if Class is None:
        raise Http404("can not find model: %s/%s" % (app, model))
    try:
        resource = resource_registry[Class][key]
    except KeyError:
        raise Http404("the model does not support rest views")
    obj = get_object_or_404(Class, pk=pk)
    if request.method == "GET":
        obj_list = get_list_or_404(Class, pk=pk)
        return resource.read(request, obj_list)
    elif request.method == "POST":
        # prototype 风格
        method = request.POST.get("_method", "POST").upper()
        if method == "PUT":
            return resource.update(request, obj)
        elif method == "DELETE":
            return resource.delete(request, obj)
        else:
            raise Http404("_method: %s can not be supported" % method)
    elif request.method == "PUT":
        return resource.update(request, obj)
    elif request.method == "DELETE":
        return resource.delete(request, obj)
